# Author: Yunqiao Zhang, Nemo
# Email: zhangyunqiao@gmail.com, nemo.zhp@gmail.com

from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.db.models import permalink
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import loader, Context, RequestContext

from meet001.meetup.forms import MeetupCreateForm
from meet001.meetup.models import Membership, Group, Meetup, JoinMeetup

# handle /group/<group_id>/meetup/create
@login_required
def create(request, group_id):
  # Check if this user is the admin of this group.
  # Only Admin has permission to add meetup.
  group = Group.objects.get(pk=group_id)
  if group.creator != request.user:
    return HttpResponse('No permission to create Meetup for this group')

  if request.method == "POST":
    form = MeetupCreateForm(request.POST)
    if form.is_valid():
      meetup_id = form.save(group)
      # Should redirect to meetup detail page later
      return HttpResponseRedirect('/group/' + str(group_id) 
              + '/meetup/details/' + str(meetup_id)  + '/')
    else:
      return render_to_response(
        'meetup_meetup_create.html',
        {'form': form},
        context_instance = RequestContext(request))
  else:
    form = MeetupCreateForm()
    return render_to_response(
        'meetup_meetup_create.html', 
        {'form': form},
        context_instance = RequestContext(request))

def details(request,meetup_id, group_id):
#def details(request):
  #Currently joined just have two value, actual value may have 3.
  #Stands for: Requested, Approved, Processing. Now just use a boolean.

# if not, show the 
  joined = False
  anonymous = True
  status = -1
  if not request.user.is_anonymous():
    anonymous = False
  #find whether the meetup exist
  meetups = Meetup.objects.filter(id=meetup_id)
  #if exist
  if meetups:
#    if request.user in meetups[0]
    if request.user in meetups[0].group.users.all():
      # joined this group
      joined = True
      joinMeetups = JoinMeetup.objects.filter(user=request.user, meetup=meetups[0])
      if joinMeetups.count() > 0:
        #not paticipate yet
          status = joinMeetups[0].join_status
    participants = count_participants(meetups[0])
    #display it
    return render_to_response('meetup_meetup_details.html',
                              {'meetup':meetups[0], 
                               'anonymous':anonymous,
                               'joined':joined,
                               'status':status,
                               'user':request.user,
                               'participants':participants})
  else:
    #if not exist, check whether current user is the creator
    group = Group.objects.filter(id=group_id)[0]
    if group.creator != request.user:
      return HttpResponse('''Sorry, the meetup infomation you requested does not exist\
      you can create infomation in your own group''')
#    group_id = meetups[0].group.id
    return HttpResponseRedirect('/group/%s/meetup/create' %group_id)
  
  
def participate(request, group_id):
  if request.method == "POST":
    user = request.user
    meetup = Meetup.objects.get(id=request.POST['meetup_id'])
    new_join = JoinMeetup()
    new_join.user = user
    new_join.meetup = meetup
    if cmp(request.POST['response'], u'1') == 0:
      new_join.join_status = 0
      new_join.save()
      #after join, go to the group_details page
      return HttpResponseRedirect('/group/%s/meetup/details/%s' %(group_id,meetup.id))
    elif cmp(request.POST['response'], u'2') == 0:
      new_join.join_status = 1
      new_join.save()
      return HttpResponse("Thanks! You can choose other meetups!")
    else:
      return HttpResponse("Thanks! Don't forget to make decision before the meetup!")
  
  
def count_participants(the_meetup):
  joinMeetups = JoinMeetup.objects.filter(meetup=the_meetup)
  the_group = the_meetup.group
  all = the_group.users.count()
  definite = joinMeetups.filter(join_status=0).count()
  refused = joinMeetups.filter(join_status=1).count()
  undecided = all - definite - refused;
  
#  refused = joinMeetups.filter(join_status=1).count()
  return {"definite":definite, "refused":refused, "undecided":undecided}